#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory.h>
#include <functional>
#include "Command.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include <pthread.h>
#include "pthreadpool.hpp"
using namespace PthreadPoolModule;
using namespace LogModule;
using task_t = std::function<void(void)>;
using func_t = std::function<std::string(const std::string &,InetAddr)>;
int defaultsockid = -1;

class TCP_serve : public NoCopy
{

public:
    TCP_serve(uint16_t port, func_t func)
        : _port(port), _isrunning(false), _func(func)
    {
    }
    void Init()
    {
        // 创建套接字
        _listensockid = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockid < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(ExitCode::SOCK_ERR);
        }
        LOG(LogLevel::INFO) << "socket success";
        // bind网络文件
        InetAddr local(_port);
        int n = bind(_listensockid, local.NetAddrPtr(), local.Len());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::FATAL) << "bind success";
        int backlog = 5;
        int m = listen(_listensockid, backlog);
        if (m < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }
        LOG(LogLevel::FATAL) << "listen success";
    };

   

    void serve(int sockfd, InetAddr &addr)
    {
        char buffer[1024];
        while (true)
        {
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::INFO) << addr.StringAddr() << "# " << buffer;
                // std::string echo_String = "echo# ";
                // echo_String += buffer;
               
                std::string echo_string = _func(buffer,addr);
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::ERROR) << addr.StringAddr() << "退出了。。。";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::ERROR) << addr.StringAddr() << "异常。。。";
                close(sockfd);
                break;
            }
        }
    }
     class PthreadData
    {
    public:
        PthreadData(int sockid, InetAddr addr)
            : _sockid(sockid),
              _addr(addr)
        {
        }

    public:
        int _sockid;
        InetAddr _addr;
        TCP_serve *ts;
    };

    static void *Rountine(void *args)
    {
        PthreadData *pd = static_cast<PthreadData *>(args);
        pthread_detach(pthread_self());
        pd->ts->serve(pd->_sockid, pd->_addr);
        delete pd;
        return nullptr;
    };

    void Start()
    {
        _isrunning = true;
        LOG(LogLevel::INFO) << "服务器开始运行";
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockid, CONV(peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept from>" << addr.StringAddr();
            // serve(sockfd, addr);

            // // 多线程版本TCP
            PthreadData *pd = new PthreadData(sockfd, addr);
            pd->ts = this;
            pthread_t tid;
            pthread_create(&tid, nullptr, Rountine, pd);

            //线程池--version
            //Pthreadpool<task_t>::GetInstance()->Enqueue([this, sockfd, &addr]()
            //                                            { this->serve(sockfd, addr); });
        }
    };
    ~TCP_serve() {}

private:
    std::string _ip;
    uint16_t _port;
    int _listensockid;
    bool _isrunning;

    func_t _func;
};